package org.frog.commons.util;

/**
 * byte和short、int、long之间的转换
 * 
 * @author duanxiangqi
 * @date 2012-11-4
 */
public final class NumberUtil {

	private NumberUtil() {}

	public static byte[] short2bytes(short s) {
		byte[] shortBuf = new byte[2];
		for (int i = 0; i < 2; i++) {
			int offset = (shortBuf.length - 1 - i) * 8;
			shortBuf[i] = (byte) ((s >>> offset) & 0xff);
		}
		return shortBuf;
	}

	public static int bytes2short(byte[] b) {
		return (b[0] << 8) + (b[1] & 0xFF);
	}

	public static byte[] int2bytes(int value) {
		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			int offset = (b.length - 1 - i) * 8;
			b[i] = (byte) ((value >>> offset) & 0xFF);
		}
		return b;
	}

	public static int bytes2int(byte[] b) {
		return (b[0] << 24) + (b[1] << 16) + (b[2] << 8) + (b[3] & 0xFF);
	}

	public static byte[] long2bytes(long value) {
		byte[] b = new byte[8];
		for (int i = 0; i < 8; i++) {
			int offset = (b.length - 1 - i) * 8;
			b[i] = (byte) ((value >>> offset) & 0xFF);
		}
		return b;
	}

	public static long bytes2long(byte[] b) {
		return (b[0] << 56) + (b[1] << 48) + (b[2] << 40) + (b[3] << 32) + (b[4] << 24) + (b[5] << 16) + (b[6] << 8)
				+ (b[7] & 0xFF);
	}
}
